<?php
class IndexAction extends CommonAction {

    /**
     * 首页
     * @return void
     */
    public function index(){
        //搜索类型
        $textType = $this->_get('st','intval',1);
        //搜索模式
        $searchMode = $this->_get('sm','intval',3);
        //搜索内容
        $text = $this->_get('k');
        //默认搜索参数
        $this->assign('initSearcher',json_encode(['textType'=>$textType,'searchMode'=>$searchMode,'text'=>$text,'sqNum'=>'1-150']));
        $this->assign('initCategory',json_encode($this->getCategory()));
        $this->display('Index:index');
    }


    /**
     * AJAX 搜索
     * @return JSON
     */
    public function search(){
        //分页参数
        $pageCurrent = $this->_post('current', 'intval');
        $pageLimit = $this->_post('limit', 'intval');
        //价格由低到高
        $orderBy = $this->_post("orderBy", "intval");
        //同名标仅显示一个类别
        $distinct = $this->_post("distinct", "intval");
        //分页
        $this->M->page['no'] = $pageCurrent;
        $this->M->page['num'] = $pageLimit;
        //SQL条件
        $where = $this->searchWhere();
        $whereText = $this->searchWhereText();
        $whereStr = implode(" AND ", $where) . $whereText;
        $timeStart = microtime(true);
        //Count
        $total = $this->getWhereTotal($distinct,$whereStr);
        //结果
        $list = [];
        if($total > 0){
            //SQL拼装
            $orderStr = $orderBy ? "m.trademark_price ASC, m.trademark_name_combined_type_order DESC" : "m.trademark_name_combined_type_order DESC, m.trademark_price ASC ";
            $groupStr = $distinct ? "trademark_name" : "CONCAT(m.trademark_name,m.trademark_sn)";

            //$field = "m.id,m.trademark_sn,m.trademark_name,m.trademark_cate,m.trademark_price,m.thumb_image,m.trademark_image,m.trademark_group_sn,m.trademark_goods_name, tgsi.group_sn,tgsi.goods_sn,tgsi.goods_chinese_name,";
            //$field.= "COUNT(distinct tgsi.goods_chinese_name) count_goods_service";
            //$SQL = "SELECT {$field} FROM trademarks m LEFT JOIN trademark_goods_service_info tgsi ";
            //$SQL.= "ON m.trademark_sn = tgsi.trademark_sn and m.trademark_cate = tgsi.trademark_cate WHERE {$whereStr} GROUP BY {$groupStr}";

            $field = "m.id,m.trademark_sn,m.trademark_name,m.trademark_cate,m.trademark_price,m.thumb_image,m.trademark_image,m.trademark_group_sn,m.trademark_goods_name";
            $SQL = "SELECT {$field} FROM trademarks m WHERE {$whereStr} GROUP BY {$groupStr}";
            $list = M()->query("{$SQL} ORDER BY {$orderStr} LIMIT " . $this->page_limit());
            if(!empty($list)){
                foreach ($list AS $key => $val){
                    $list[$key]['count_goods_service'] = 0;
                    if( !empty($val['trademark_goods_name']) ){
                        $trademark_goods_name = json_decode($val['trademark_goods_name'],true);
                        $list[$key]['count_goods_service'] = count($trademark_goods_name);
                    }
                }
            }
            //echo M()->_sql();
        }
        $timeEnd = microtime(true);
        //响应
        $result = ['code'=>0, 'msg'=>'', 'data'=>['total'=> $total, 'results'=> $list, 'ts'=>$timeEnd-$timeStart]];
        echo json_encode($result);
        exit;
    }

    /**
     * 获取 where 条件数组
     * @return array
     */
    private function searchWhere(){
        //价格范围
        $priceStart = $this->_post("priceStart","intval");
        $priceEnd = $this->_post("priceEnd","intval");
        //商标类别 array
        $leis = $_POST["leis"];
        //类似群组 array
        $teams = $_POST["teams"];
        //产品/服务
        $goods = $_POST["goods"];
        //组合类型 array
        $types = $_POST["types"];
        //商标字数 array
        $nameSize = $_POST["nameSize"];
        //申请人类型 1、公司，2、个人
        $sqType = $this->_post("sqType", "intval");
        //注册人申请量 1-150 【String】
        $sqNum = $this->_post("sqNum");
        //注册年限
        $ageStart = $this->_post("ageStart"); //开始时间
        $ageEnd = $this->_post("ageEnd"); //结束时间
        //名称结构
        $abTypes = $_POST["abTypes"];
        //拼装SQL
        //默认条件
        $defaultWhere = "m.is_deleted = 0 AND m.status = 1 AND m.image_status = 1";
        $where[] = $defaultWhere;
        //申请人类型
        if($sqType){
            $where[] = "m.trademark_register_user_type = {$sqType}";
        }
        //分类
        if( is_array($leis) ){
            foreach ($leis as $k => $v)  $leis[$k] = intval($v);
            $leiStr = implode(",", $leis);
            $where[] = "m.trademark_cate IN ({$leiStr})";
            /**
             * TODO
             * 1、同名标搜索时暂不支持添加小项
             * 2、查找不唯一的trademark_sn
             */
            if(count($leis) > 1){
                $goods = [];//清空
                //所选分类下不存在同名商标。不再进行查找
                $result = M()->query("SELECT GROUP_CONCAT(m.trademark_sn) trademarks,count(m.id) AS count FROM trademarks m WHERE {$defaultWhere} AND m.trademark_cate IN ({$leiStr}) GROUP BY m.trademark_name HAVING count = " . count($leis));
                if(empty($result)){
                    $where[] = "m.id = 0";
                }else{
                    $sns = [];
                    foreach ($result as $item){
                        foreach (explode(",",$item['trademarks']) as $sn) array_push($sns, $sn);
                    }
                    $where[] = "m.trademark_sn IN ('" .implode("','", $sns ). "')";
                }
            }
        }
        //类似群组
        if( is_array($teams) ){
            $i = 1;
            $where_group_sn = '';
            foreach ($teams as $k => $v){
                $groupSn = htmlspecialchars($v);
                if($i < count($teams)){
                    $where_group_sn .= " m.trademark_group_sn like '%\"".$groupSn."\"%'  AND  ";
                }else{
                    $where_group_sn .= " m.trademark_group_sn like '%\"".$groupSn."\"%' ";
                }
                $i++;
            }
            if( !empty($where_group_sn) ){
                $where[] = "(" . $where_group_sn . ")";
            }
            //foreach ($teams as $k => $v) $teams[$k] = htmlspecialchars($v);
            //$where[] = "tgsi.group_sn IN ('". implode("','", $teams) ."')";
        }
        //组合类型
        if( is_array($types) ){
            $where[] = "m.trademark_name_combined_type IN ('". implode("','", $types) ."')";
        }
        //商标字数
        if( is_array($nameSize) ){
            $where[] = "m.trademark_name_length IN ('". implode("','", $nameSize) ."')";
        }
        //名称结构
        if( is_array($abTypes) ){
            $where[] = "m.trademark_name_struct_type IN ('". implode("','", $abTypes) ."')";
        }
        //价格
        if( $priceStart < $priceEnd ){
            $where[] = "m.trademark_price BETWEEN {$priceStart} AND {$priceEnd}";
        }else if($priceStart > 0 || $priceEnd > 0){
            $where[] = "m.trademark_price BETWEEN {$priceEnd} AND {$priceStart}";
        }
        //商标年限
        if( !(empty($ageStart) && empty($ageEnd)) ){
            if(empty($ageEnd)){
                $etime = date("Y-m-d H:i:s",strtotime("-{$ageStart} year", time()));
                $where[] = "m.trademark_apply_time <= '{$etime}'";
            }else{
                $stime = date("Y-m-d H:i:s",strtotime("-{$ageEnd} year", time()));
                $etime = date("Y-m-d H:i:s",strtotime("-{$ageStart} year", time()));
                $where[] = "m.trademark_apply_time BETWEEN '{$stime}' AND '{$etime}'";
            }
        }
        //产品/服务
        if(!empty($goods)){
            $i = 1;
            $where_goods_name= '';
            foreach ($goods as $k => $v){
                $goodsName = htmlspecialchars(trim($v));
                if($i < count($goods)){
                    $where_goods_name .= " m.trademark_goods_name like '%\"".$goodsName."\"%'  AND  ";
                }else{
                    $where_goods_name .= " m.trademark_goods_name like '%\"".$goodsName."\"%' ";
                }
                $i++;
            }
            if( !empty($where_goods_name) ){
                $where[] = "(" . $where_goods_name . ")";
            }
            //foreach ($goods as $k => $v) $goods[$k] = htmlspecialchars(trim($v));
            //$where[] = "tgsi.goods_chinese_name IN ('". implode("','", $goods) ."')";
        }

        return $where;
    }

    /**
     * 搜索 where 关键字
     * @return string
     */
    private function searchWhereText(){
        //搜索类型
        $textType = $this->_post("textType");
        //搜索模式
        $searchMode = $this->_post("searchMode");
        //搜索内容
        $text = $this->_post("text");
        //搜索关键词
        $textStr = "";
        if( !empty($text) ){
            $textStr = " AND ( " . $this->getWhereSearchKeywordStr($searchMode, $textType ,$text) . " )";
        }
        return $textStr;
    }

    /**
     * 获取搜索关键词WHERE条件
     *
     * @param [type] $sm
     * @param [type] $st
     * @param [type] $keywords
     * @return string
     */
    private function getWhereSearchKeywordStr($sm, $st, $keywords){
        $where = [];
        if( $sm == 0 || $sm == 3 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name like '%{$keywords}%'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn like '%{$keywords}%'";
            }elseif( $st == 3  ){
                //申请人
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}%'";
            }elseif( $st == 0  ){
                //智能
                $where[] = "m.trademark_name like '%{$keywords}%'";
                $where[] = "m.trademark_sn like '%{$keywords}%'";
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}%'";
            }
        }elseif( $sm == 1 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name like '{$keywords}%'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn like '{$keywords}%'";
            }elseif( $st == 3  ){
                $where[] = "m.trademark_register_chinese_name like '{$keywords}%'";
            }elseif( $st == 0  ){
                $where[] = "m.trademark_name like '{$keywords}%'";
                $where[] = "m.trademark_sn like '{$keywords}%'";
                $where[] = "m.trademark_register_chinese_name like '{$keywords}%'";
            }
        }elseif( $sm == 2 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name like '%{$keywords}'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn like '%{$keywords}'";
            }elseif( $st == 3  ){
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}'";
            }elseif( $st == 0  ){
                $where[] = "m.trademark_name like '%{$keywords}'";
                $where[] = "m.trademark_sn like '%{$keywords}'";
                $where[] = "m.trademark_register_chinese_name like '%{$keywords}'";
            }
        }elseif( $sm == 4 ){
            if( $st == 1 ){
                $where[] = "m.trademark_name = '{$keywords}'";
            }elseif( $st == 2  ){
                $where[] = "m.trademark_sn = '{$keywords}'";
            }elseif( $st == 3  ){
                $where[] = "m.trademark_register_chinese_name = '{$keywords}'";
            }elseif( $st == 0  ){
                $where[] = "m.trademark_name = '{$keywords}'";
                $where[] = "m.trademark_sn = '{$keywords}'";
                $where[] = "m.trademark_register_chinese_name = '{$keywords}'";
            }
        }
        return implode(" OR ",$where);
    }


    /**
     * 根据where条件缓存count值
     * @param $distinct
     * @param $whereStr
     * @return int
     * 默认key从Redis获取
     */
    private function getWhereTotal($distinct,$whereStr){
        $countDistinct = $distinct ? "m.trademark_name" : "m.trademark_name,m.trademark_sn";
        //$cacheKey = md5($countDistinct.':'.$whereStr);
        //首页默认KEY、优先从Redis获取
        //if($cacheKey == "f3b39e04f7eeab8679d6863f6565e934"){
            //$total = intval($this->redis_cache->get($cacheKey));
            //if ($total > 0) return $total;
        //}
        //$sessionKey = 'indexCountMap';
        //if(isset($_SESSION[$sessionKey][$cacheKey])){
            //return intval($_SESSION[$sessionKey][$cacheKey]);
        //}else{
            //$SQL = "SELECT COUNT(distinct {$countDistinct}) AS total FROM trademarks m LEFT JOIN trademark_goods_service_info tgsi ";
            //$SQL.= "ON m.trademark_sn = tgsi.trademark_sn and m.trademark_cate = tgsi.trademark_cate WHERE {$whereStr}";
            $SQL = "SELECT COUNT(distinct {$countDistinct}) AS total FROM trademarks m WHERE {$whereStr}";
            $countResult = M()->query($SQL);
            $total = $countResult[0]['total'];
            //if($total >0) $_SESSION[$sessionKey][$cacheKey] = $total;
            return $total;
        //}
    }
}